package com.example.service.impl;

import com.example.common.PageResult;
import com.example.common.Result;
import com.example.dto.SalesRecordDTO;
import com.example.dto.SalesRecordQueryDTO;
import com.example.entity.SalesRecord;
import com.example.entity.StockRecord;
import com.example.entity.StoreProduct;
import com.example.entity.SupplyProduct;
import com.example.mapper.SalesRecordMapper;
import com.example.mapper.StockRecordMapper;
import com.example.mapper.StoreProductMapper;
import com.example.mapper.SupplyProductMapper;
import com.example.service.SalesRecordService;
import com.example.util.UserContextUtil;
import com.example.vo.SalesRecordVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 商品售卖记录Service实现类
 */
@Slf4j
@Service
public class SalesRecordServiceImpl implements SalesRecordService {

    @Autowired
    private SalesRecordMapper salesRecordMapper;

    @Autowired
    private StoreProductMapper storeProductMapper;

    @Autowired
    private SupplyProductMapper supplyProductMapper;

    @Autowired
    private StockRecordMapper stockRecordMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    @Transactional
    public Result<Void> addSalesRecord(SalesRecordDTO salesRecordDTO) {
        try {
            // 获取当前店长ID
            Long storeManagerId = userContextUtil.getCurrentUserId();
            if (storeManagerId == null) {
                return Result.error("用户未登录");
            }

            // 查询店长商品信息
            StoreProduct storeProduct = storeProductMapper.selectById(salesRecordDTO.getStoreProductId());
            if (storeProduct == null) {
                return Result.error("商品不存在");
            }

            // 验证是否是当前店长的商品
            if (!storeProduct.getStoreManagerId().equals(storeManagerId)) {
                return Result.error("无权限操作该商品");
            }

            // 检查库存是否充足
            if (storeProduct.getCurrentStock() < salesRecordDTO.getSaleQuantity()) {
                return Result.error("库存不足，当前库存：" + storeProduct.getCurrentStock());
            }

            // 查询供货商品信息
            SupplyProduct supplyProduct = supplyProductMapper.selectById(storeProduct.getSupplyProductId());
            if (supplyProduct == null) {
                return Result.error("供货商品信息不存在");
            }

            // 计算总金额和利润
            BigDecimal unitPrice = salesRecordDTO.getUnitPrice() != null ? 
                salesRecordDTO.getUnitPrice() : storeProduct.getSellingPrice();
            BigDecimal totalAmount = unitPrice.multiply(new BigDecimal(salesRecordDTO.getSaleQuantity()));
            BigDecimal costPrice = supplyProduct.getCost();
            BigDecimal totalCost = costPrice.multiply(new BigDecimal(salesRecordDTO.getSaleQuantity()));
            BigDecimal profit = totalAmount.subtract(totalCost);

            // 创建售卖记录
            SalesRecord salesRecord = new SalesRecord();
            salesRecord.setRecordNo(generateRecordNo());
            salesRecord.setStoreManagerId(storeManagerId);
            salesRecord.setStoreProductId(storeProduct.getId());
            salesRecord.setSupplyProductId(storeProduct.getSupplyProductId());
            salesRecord.setProductName(storeProduct.getProductName());
            salesRecord.setProductCode(storeProduct.getProductCode());
            salesRecord.setSaleQuantity(salesRecordDTO.getSaleQuantity());
            salesRecord.setUnitPrice(unitPrice);
            salesRecord.setTotalAmount(totalAmount);
            salesRecord.setCostPrice(costPrice);
            salesRecord.setProfit(profit);
            salesRecord.setCustomerName(salesRecordDTO.getCustomerName());
            salesRecord.setCustomerPhone(salesRecordDTO.getCustomerPhone());
            salesRecord.setSaleStatus(1); // 已完成
            salesRecord.setRemark(salesRecordDTO.getRemark());
            salesRecord.setCreateTime(LocalDateTime.now());
            salesRecord.setUpdateTime(LocalDateTime.now());
            salesRecord.setDeleted(0);

            // 保存售卖记录
            int result = salesRecordMapper.insert(salesRecord);
            if (result <= 0) {
                return Result.error("售卖记录保存失败");
            }

            // 更新店长商品库存（减少）
            int beforeStock = storeProduct.getCurrentStock();
            int afterStock = beforeStock - salesRecordDTO.getSaleQuantity();
            storeProductMapper.updateStock(storeProduct.getId(), afterStock);

            // 自动创建出库记录
            createStockOutRecord(storeProduct, salesRecordDTO.getSaleQuantity(), 
                beforeStock, afterStock, "商品售卖出库", storeManagerId);

            log.info("商品售卖成功，售卖记录ID: {}, 商品: {}, 数量: {}, 总金额: {}", 
                salesRecord.getId(), storeProduct.getProductName(), 
                salesRecordDTO.getSaleQuantity(), totalAmount);

            return Result.success();
        } catch (Exception e) {
            log.error("添加售卖记录失败", e);
            return Result.error("添加售卖记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PageResult<SalesRecordVO>> getPageList(SalesRecordQueryDTO queryDTO) {
        try {
            // 获取当前用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }

            // 设置分页参数
            PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());

            List<SalesRecordVO> records;
            long total;

            // 判断是否是管理员（这里简单判断，实际可以根据角色判断）
            // 如果是店长，只查询自己的售卖记录
            records = salesRecordMapper.selectStoreManagerSalesPage(
                currentUserId,
                queryDTO.getRecordNo(),
                queryDTO.getProductName(),
                queryDTO.getProductCode(),
                queryDTO.getCustomerName(),
                queryDTO.getCustomerPhone(),
                queryDTO.getSaleStatus(),
                queryDTO.getStartTime(),
                queryDTO.getEndTime()
            );

            total = salesRecordMapper.countStoreManagerSales(
                currentUserId,
                queryDTO.getRecordNo(),
                queryDTO.getProductName(),
                queryDTO.getProductCode(),
                queryDTO.getCustomerName(),
                queryDTO.getCustomerPhone(),
                queryDTO.getSaleStatus(),
                queryDTO.getStartTime(),
                queryDTO.getEndTime()
            );

            // 设置状态名称
            records.forEach(record -> record.setSaleStatusName(record.getSaleStatusName()));

            PageResult<SalesRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(records);
            pageResult.setTotal(total);
            pageResult.setCurrent(queryDTO.getPage());
            pageResult.setSize(queryDTO.getSize());
            pageResult.setPages((int) Math.ceil((double) total / queryDTO.getSize()));

            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询售卖记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<SalesRecordVO> getSalesRecordById(Long id) {
        try {
            SalesRecordVO record = salesRecordMapper.selectVOById(id);
            if (record == null) {
                return Result.error("售卖记录不存在");
            }

            // 验证权限（只能查看自己的记录）
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }

            if (!record.getStoreManagerId().equals(currentUserId)) {
                return Result.error("无权限查看该记录");
            }

            record.setSaleStatusName(record.getSaleStatusName());
            return Result.success(record);
        } catch (Exception e) {
            log.error("查询售卖记录详情失败，ID: {}", id, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> cancelSalesRecord(Long id) {
        try {
            // 查询售卖记录
            SalesRecord record = salesRecordMapper.selectById(id);
            if (record == null) {
                return Result.error("售卖记录不存在");
            }

            // 验证权限
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }

            if (!record.getStoreManagerId().equals(currentUserId)) {
                return Result.error("无权限操作该记录");
            }

            // 检查记录状态
            if (record.getSaleStatus() != 1) {
                return Result.error("只能取消已完成的售卖记录");
            }

            // 更新记录状态为已取消
            record.setSaleStatus(2);
            record.setUpdateTime(LocalDateTime.now());
            salesRecordMapper.updateById(record);

            // 恢复商品库存
            StoreProduct storeProduct = storeProductMapper.selectById(record.getStoreProductId());
            if (storeProduct != null) {
                int beforeStock = storeProduct.getCurrentStock();
                int afterStock = beforeStock + record.getSaleQuantity();
                storeProductMapper.updateStock(storeProduct.getId(), afterStock);

                // 创建入库记录（取消售卖恢复库存）
                createStockInRecord(storeProduct, record.getSaleQuantity(), 
                    beforeStock, afterStock, "取消售卖恢复库存", currentUserId);
            }

            log.info("取消售卖记录成功，记录ID: {}", id);
            return Result.success();
        } catch (Exception e) {
            log.error("取消售卖记录失败，ID: {}", id, e);
            return Result.error("取消失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<SalesRecordVO>> exportSalesRecords(SalesRecordQueryDTO queryDTO) {
        try {
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }

            List<SalesRecordVO> records = salesRecordMapper.selectStoreManagerSalesPage(
                currentUserId,
                queryDTO.getRecordNo(),
                queryDTO.getProductName(),
                queryDTO.getProductCode(),
                queryDTO.getCustomerName(),
                queryDTO.getCustomerPhone(),
                queryDTO.getSaleStatus(),
                queryDTO.getStartTime(),
                queryDTO.getEndTime()
            );

            records.forEach(record -> record.setSaleStatusName(record.getSaleStatusName()));
            return Result.success(records);
        } catch (Exception e) {
            log.error("导出售卖记录失败", e);
            return Result.error("导出失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<SalesRecordVO>> getSalesRecordsByProductId(Long productId) {
        try {
            List<SalesRecordVO> records = salesRecordMapper.selectByProductId(productId);
            records.forEach(record -> record.setSaleStatusName(record.getSaleStatusName()));
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据商品ID查询售卖记录失败，商品ID: {}", productId, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<SalesRecordVO>> getMySalesRecords() {
        try {
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("用户未登录");
            }

            List<SalesRecordVO> records = salesRecordMapper.selectByStoreManagerId(currentUserId);
            records.forEach(record -> record.setSaleStatusName(record.getSaleStatusName()));
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取我的售卖记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 创建出库记录
     */
    private void createStockOutRecord(StoreProduct storeProduct, Integer quantity, 
                                     Integer beforeStock, Integer afterStock, 
                                     String remark, Long operatorId) {
        try {
            // 获取操作员姓名
            String operatorName = userContextUtil.getCurrentUserNickname();
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "系统用户";
                }
            }

            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            // 使用供货商品ID，保持与入库明细管理的记录一致
            stockRecord.setProductId(storeProduct.getSupplyProductId());
            stockRecord.setProductName(storeProduct.getProductName());
            stockRecord.setProductCode(storeProduct.getProductCode());
            stockRecord.setRecordType("OUT"); // 出库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName(operatorName + "(店长出库)"); // 标识为店长出库，使其显示在店长端
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);

            stockRecordMapper.insert(stockRecord);
            log.info("创建出库记录成功，商品: {}, 数量: {}", storeProduct.getProductName(), quantity);
        } catch (Exception e) {
            log.error("创建出库记录失败", e);
        }
    }

    /**
     * 创建入库记录
     */
    private void createStockInRecord(StoreProduct storeProduct, Integer quantity, 
                                    Integer beforeStock, Integer afterStock, 
                                    String remark, Long operatorId) {
        try {
            // 获取操作员姓名
            String operatorName = userContextUtil.getCurrentUserNickname();
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "系统用户";
                }
            }

            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            // 使用供货商品ID，保持与入库明细管理的记录一致
            stockRecord.setProductId(storeProduct.getSupplyProductId());
            stockRecord.setProductName(storeProduct.getProductName());
            stockRecord.setProductCode(storeProduct.getProductCode());
            stockRecord.setRecordType("IN"); // 入库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName(operatorName + "(店长入库)"); // 标识为店长入库，使其显示在店长端
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);

            stockRecordMapper.insert(stockRecord);
            log.info("创建入库记录成功，商品: {}, 数量: {}", storeProduct.getProductName(), quantity);
        } catch (Exception e) {
            log.error("创建入库记录失败", e);
        }
    }

    /**
     * 生成售卖记录编号
     */
    private String generateRecordNo() {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        return "SALE" + dateStr + random;
    }

    /**
     * 生成库存记录编号
     */
    private String generateStockRecordNo() {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        return "SR" + dateStr + random;
    }
} 